package com.xincongjun.media.rename;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import static com.xincongjun.media.utils.DateTimeUtil.*;
import static com.xincongjun.media.utils.ExifToolUtil.useExifToolReadJpgOrMp4Time;
import static com.xincongjun.media.utils.ExifToolUtil.useExifToolUpdateTime;
import static com.xincongjun.media.utils.FileUtil.*;
import static com.xincongjun.media.utils.ParseDateTimeFromFilenameUtil.*;
import static com.xincongjun.media.utils.PowerShellUtil.usePowerShellUpdateTime;

public class RenameFile {

    private static final Logger logger = LoggerFactory.getLogger(RenameFile.class);

    public static void renameJpgOrMp4File(String directoryPath) {
        File dir = new File(directoryPath);
        if (!dir.exists() || !dir.isDirectory()) {
            logger.error("无效路径: {}", directoryPath);
            return;
        }

        File[] files = dir.listFiles();
        if (files == null || files.length == 0) {
            logger.error("路径下不存在文件: {}", directoryPath);
            return;
        }

        String failDirectory = directoryPath + File.separator + "fail";
        File failFile = new File(failDirectory);
        if (!failFile.exists()) {
            failFile.mkdirs();
        }else {
            deleteDirectory(failFile);
            failFile.mkdirs();
        }

        for (File file : files) {
            if (file.isFile()) {
                renameJpgOrMp4FileProcessFile(file, failFile);
            }
        }

        File[] failFiles = failFile.listFiles();
        if (failFiles == null || failFiles.length == 0) {
            deleteDirectory(failFile);
        }

        logger.info("所有文件处理完成！");
    }

    private static void renameJpgOrMp4FileProcessFile(File file, File failFile) {
        String filePath = file.getAbsolutePath();
        String failFilePath = failFile.getAbsolutePath();

        try {
            String dateTimeOriginal = useExifToolReadJpgOrMp4Time(filePath);
            if (dateTimeOriginal == null || dateTimeOriginal.isEmpty() || dateTimeOriginal.equals("0000:00:00 00:00:00")) {
                moveFileToDirectory(filePath, failFilePath);
                return;
            }
            String newDateTimeOriginal = convertDateFormat(dateTimeOriginal, EXIF_TIME_PATTERN, FILE_RENAME_TIME_PATTERN);

            String prefix = "media";
            String infix = newDateTimeOriginal;
            String suffix = generateRandomSixDigitNumberString();
            String separator = "_";
            String extension = getFileExtension(filePath);

            renameFile(filePath, prefix, infix, suffix, separator);

            List<String> parts = new ArrayList<>();
            parts.add(prefix);
            parts.add(infix);
            parts.add(suffix);
            String fileName = String.join(separator, parts);
            String newFilePath = file.getParentFile() + File.separator + fileName + "." + extension;

            String fileTime = convertDateFormat(dateTimeOriginal, EXIF_TIME_PATTERN, STANDARD_TIME_PATTERN);

            if (getRealFileType(newFilePath).equalsIgnoreCase("jpg")) {
                usePowerShellUpdateTime(newFilePath, fileTime);
            }else if (getRealFileType(newFilePath).equalsIgnoreCase("mp4")){
                fileTime = convertToTargetTimeZone(fileTime, ZONE_UTC, ZONE_LOCAL, STANDARD_TIME_PATTERN);
                usePowerShellUpdateTime(newFilePath, fileTime);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void parseFileNameRename(String directoryPath) {
        File dir = new File(directoryPath);
        if (!dir.exists() || !dir.isDirectory()) {
            logger.error("无效路径: {}", directoryPath);
            return;
        }

        File[] files = dir.listFiles();
        if (files == null || files.length == 0) {
            logger.error("路径下不存在文件: {}", directoryPath);
            return;
        }

        String failDirectory = directoryPath + File.separator + "fail";
        File failFile = new File(failDirectory);
        if (!failFile.exists()) {
            failFile.mkdirs();
        }else {
            deleteDirectory(failFile);
            failFile.mkdirs();
        }

        for (File file : files) {
            if (file.isFile()) {
                parseFileNameRenameProcessFile(file, failFile);
            }
        }

        File[] failFiles = failFile.listFiles();
        if (failFiles == null || failFiles.length == 0) {
            deleteDirectory(failFile);
        }

        logger.info("所有文件处理完成！");
    }

    private static void parseFileNameRenameProcessFile(File file, File failFile) {
        String filePath = file.getAbsolutePath();
        String failFilePath = failFile.getAbsolutePath();
        String fileName = getFileName(filePath);

        try {
            if (!getRealFileType(filePath).equalsIgnoreCase("jpg") && !getRealFileType(filePath).equalsIgnoreCase("mp4")) {
                moveFileToDirectory(filePath, failFilePath);
                return;
            }
            // TODO 解析文件名
            String timeStr = parseFileNameToTimestamp01(fileName);
            String newTimeStr = convertDateFormat(timeStr, STANDARD_TIME_PATTERN, FILE_RENAME_TIME_PATTERN);

            String prefix = "media";
            String infix = newTimeStr;
            String suffix = generateRandomSixDigitNumberString();
            String separator = "_";
            String extension = getFileExtension(filePath);

            renameFile(filePath, prefix, infix, suffix, separator);

            List<String> parts = new ArrayList<>();
            parts.add(prefix);
            parts.add(infix);
            parts.add(suffix);
            String newFileName = String.join(separator, parts);
            String newFilePath = file.getParentFile() + File.separator + newFileName + "." + extension;

            if (getRealFileType(newFilePath).equalsIgnoreCase("jpg")) {
                useExifToolUpdateTime(newFilePath, timeStr, ZONE_LOCAL, null);
                usePowerShellUpdateTime(newFilePath, timeStr);
            }else if (getRealFileType(newFilePath).equalsIgnoreCase("mp4")){
                useExifToolUpdateTime(newFilePath, timeStr, ZONE_UTC, null);
                usePowerShellUpdateTime(newFilePath, timeStr);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
